package org.mech.sefer.client.i18n;

import java.util.Locale;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.context.ApplicationListener;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.stereotype.Component;

/**
 * <p>
 * The I18n is bean responsible for i18n of texts in applications. It uses
 * spring message source interface. When language change it propagates change to
 * all registered {@link I18nAware} objects.
 * </p>
 * <p>
 * Date: 2.5.2012 17:03:16
 * </p>
 * 
 * @author martin.krajc
 */
@Component("i18n")
public class I18n implements MessageSourceAware,
		ApplicationListener<ContextStartedEvent> {

	private Locale locale = null;
	private String languageKey;
	private MessageSource messageSource;

	public I18n() {
		super();
	}

	@Resource(name = "i18nAwareProcessor")
	private I18nAwareRegisterProcessor i18nAwareRegister;

	@PostConstruct
	public void init() {

		if (languageKey == null) {
			locale = Locale.getDefault();
		} else {
			locale = new Locale(languageKey);
		}
	}

	public String get(String key) {
		return get(key, (String[]) null);
	}

	public String get(String key, String... params) {
		final String message = messageSource.getMessage(key, params, locale);
		System.out.println("getting ["+key+"] in locale ["+locale+"] : " + message);
		return message;
	}

	@Override
	public void setMessageSource(MessageSource messagesource) {
		this.messageSource = messagesource;
	}

	public String get(Class<?> clazz, String string) {
		return get(clazz, string, (String[]) null);
	}

	public String get(Class<?> clazz, String string, String... params) {
		return get(clazz.getName().toLowerCase().concat(".").concat(string),
				params);
	}

	@Override
	public void onApplicationEvent(ContextStartedEvent event) {
		i18nAwareRegister.propagate(this);
	}

	public void setLanguageKey(String languageKey) {
		this.languageKey = languageKey;
		init();
		i18nAwareRegister.propagate(this);
	}
}
